import { FairyEditor, FairyGUI, System, UnityEngine } from "csharp";
import File from "../io/File";

/**
 * 文件处理工具
 * @author clong 2020.11.28
 */
export default class FileUtils {

    /**
     * 浏览目录并且打开文件
     * @param handler 
     */
    public static BrowseForOpen(title: string = "打开文件", directory: string = "", handler: Laya.Handler = null): void {

        let url = directory || System.IO.Directory.GetCurrentDirectory();
        FairyEditor.IOUtil.BrowseForOpen(title, url, null, (file) => {
            if (handler != null) {
                handler.runWith(file);
            }
        });
    }

    /**
     * 浏览目录
     * @param title 
     * @param handler 
     */
    public static BrowseForDirectory(handler: Laya.Handler = null, title: string = "打开目录"): void {

        FairyEditor.IOUtil.BrowseForDirectory(title, (file) => {
            if (handler != null) {
                handler.runWith(file);
            }
        });
    }

    /**
     * 保存图片
     * @param tex 
     * @param url 
     */
    public static savePic(tex:UnityEngine.Texture2D , url: string): void {//FairyGUI.NTexture

        let path:string = url.substr( 0 , url.lastIndexOf("\\") );
        if (!System.IO.Directory.Exists(path)){
            System.IO.Directory.CreateDirectory(path);
        }
        if (!System.IO.File.Exists(url)) {
            System.IO.File.Create(url).Dispose();
        }
        try {

            let tex2d: UnityEngine.Texture2D = tex;// tex.nativeTexture as UnityEngine.Texture2D;
            
            this.SaveTextureToPNG(tex2d, url);

            console.log("保存图片成功: url: " + url + " tex2d.width: " + tex2d.width + " tex2d.height:  " + tex2d.height);

            // let tex2d:UnityEngine.Texture2D = this.duplicateTexture( tex.nativeTexture as UnityEngine.Texture2D );
            // // let tex2d:UnityEngine.Texture2D = tex.nativeTexture as UnityEngine.Texture2D;
            // if( tex2d ){
            //     // tex2d.isReadable = true;
            //     let bytes =UnityEngine.ImageConversion.EncodeToPNG( tex2d );// tex2d.GetRawTextureData();
            //     // System.IO.File.WriteAllBytes( url , bytes );
            //     let file:System.IO.FileStream  = System.IO.File.OpenWrite( url );//, System.IO.FileMode.Create           
            //     let writer:System.IO.BinaryWriter  = new System.IO.BinaryWriter(file);
            //     writer.Write(bytes);
            //     file.Close();
            //     console.log("保存图片成功: url: " + url );
            // }else{
            //     console.error("------>保存图片失败: " + url );
            // }
        } catch (error) {
            console.error("------>保存图片失败 error: " + error);
        }
    }

    public static duplicateTexture(source: UnityEngine.Texture2D): UnityEngine.Texture2D {
        let renderTex: UnityEngine.RenderTexture = UnityEngine.RenderTexture.GetTemporary(
            source.width, source.height, 0);
        // 0,
        // UnityEngine.RenderTextureFormat.Default,
        // UnityEngine.RenderTextureReadWrite.Linear

        UnityEngine.Graphics.Blit(source, renderTex);
        let previous: UnityEngine.RenderTexture = UnityEngine.RenderTexture.active;
        UnityEngine.RenderTexture.active = renderTex;
        let readableText: UnityEngine.Texture2D = new UnityEngine.Texture2D(source.width, source.height, UnityEngine.TextureFormat.ARGB32, false);
        readableText.ReadPixels(new UnityEngine.Rect(0, 0, renderTex.width, renderTex.height), 0, 0);
        readableText.Apply();

        UnityEngine.RenderTexture.ReleaseTemporary(renderTex);
        UnityEngine.RenderTexture.active = previous;
        return readableText;
    }

    public static SaveTextureToPNG(source: UnityEngine.Texture2D, url: string): void {
        let renderTex: UnityEngine.RenderTexture = UnityEngine.RenderTexture.GetTemporary(
            source.width, source.height, 0);
        // 0,
        // UnityEngine.RenderTextureFormat.Default,
        // UnityEngine.RenderTextureReadWrite.Linear

        UnityEngine.Graphics.Blit(source, renderTex);

        this.SaveRenderTextureToPNG(renderTex, url);
    }

    //将RenderTexture保存成一张png图片
    public static SaveRenderTextureToPNG(rt: UnityEngine.RenderTexture, url: string): boolean {
        let prev: UnityEngine.RenderTexture = UnityEngine.RenderTexture.active;
        UnityEngine.RenderTexture.active = rt;
        let png: UnityEngine.Texture2D = new UnityEngine.Texture2D(rt.width, rt.height, UnityEngine.TextureFormat.ARGB32, false);
        png.ReadPixels(new UnityEngine.Rect(0, 0, rt.width, rt.height), 0, 0);
        let bytes = UnityEngine.ImageConversion.EncodeToPNG( png );// png.GetRawTextureData();//
        // if (!System.IO.Directory.Exists(contents)){
        //     System.IO.Directory.CreateDirectory(contents);
        // }   
        if (!System.IO.File.Exists(url)) {
            System.IO.File.Create(url).Dispose();
        }
        let file: System.IO.FileStream = System.IO.File.Open(url, System.IO.FileMode.Create);
        let writer: System.IO.BinaryWriter = new System.IO.BinaryWriter(file);
        writer.Write(bytes);
        file.Close();
        // UnityEngine.Texture2D.DestroyImmediate(png);
        png = null;
        UnityEngine.RenderTexture.active = prev;
        return true;
    }

    /**
     * 打开本地目录
     * @param url 
     */
    public static openLocalFile(url: string): void {

        FairyEditor.BuilderUtil.RevealInExplorer(url);
    }

    /**
     * 遍历所有文件及目录
     * @param	file	文件目录
     * @param 	format	要遍历的文件后缀名
     * @param 	files	当前目录的列表
     * @param 	func	遍历时触发
     * @param 	funcParams 遍历方法参数
     * @param 	list 	所有目录列表
     */
    public static loopFiles(file: File, format: String = "asset", func: Function = null, funcParams: Array<any> = null, files: Array<File> = null, list: Array<any> = null): Array<any> {

        list = list || [];
        if (file == null) {
            return list;
        }
        format = format.replace(/\.|\*/g, "");
        var formats: Array<string> = format.split(",");//clong 2020.5.2
        var params: Array<any> = null;
        if (file.isDirectory) {
            files = files || file.getDirectoryListing();
            while (files && files.length > 0) {
                var f: any = files.shift();
                if (f != null) {
                    if (f.isDirectory) { //目录
                        //trace( "导入目录: " + f.nativePath );						
                        FileUtils.loopFiles(f, format, func, funcParams, null, list);
                    } else if (format) {
                        if (formats.indexOf(f.extension) != -1) {//f.name.indexOf(format) != -1
                            list.push(f);
                        } else {
                            continue;
                        }
                    } else {
                        list.push(f);
                    }

                    if (func != null) {
                        params = funcParams || [];
                        params.unshift(f);
                        func.apply(null, params);
                    }
                }
            }
        } else if (!format || formats.indexOf(f.extension) != -1) {//file.name.indexOf(format) != -1
            list.push(file);
            if (func != null) {
                params = funcParams || [];
                params.unshift(file);
                func.apply(null, params);
            }
        }
        return list;
    }
}